package pers.xiaojun.boot.tenant.core.service;

import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import pers.xiaojun.boot.common.biz.system.tenant.TenantCommonApi;
import pers.xiaojun.boot.common.exception.BusinessException;
import pers.xiaojun.boot.common.util.CacheUtils;

import java.time.Duration;

/**
 * 租户服务实现类
 *
 * @author xiaojun
 * @since 2025-11-23
 */
public class TenantCommonServiceImpl implements TenantCommonService {

    private static final BusinessException BUSINESS_EXCEPTION_NULL = new BusinessException();

    private final TenantCommonApi tenantCommonApi;
    // 缓存校验租户的结果
    private final LoadingCache<Long, BusinessException> validTenantCache;

    public TenantCommonServiceImpl(TenantCommonApi tenantCommonApi) {
        this.tenantCommonApi = tenantCommonApi;
        validTenantCache = buildValidTenantCache();
    }

    /**
     * 构建校验租户的结果缓存器
     *
     * @return 本地缓存
     */
    private LoadingCache<Long, BusinessException> buildValidTenantCache() {
        return CacheUtils.buildAsyncReloadingCache(
                Duration.ofMinutes(1),
                new CacheLoader<>() {
                    @Override
                    public BusinessException load(Long key) throws Exception {
                        try {
                            tenantCommonApi.validTenantAvailable(key);
                            return BUSINESS_EXCEPTION_NULL;
                        } catch (BusinessException e) {
                            return e;
                        }
                    }
                }
        );
    }


    @Override
    @SneakyThrows
    public void validTenantAvailable(Long tenantId) {
        BusinessException businessException = validTenantCache.get(tenantId);
        if(businessException != BUSINESS_EXCEPTION_NULL) {
            throw businessException;
        }
    }

}
